#!/usr/bin/env bash
#
# author:yang
# description:安装 elk 集群

KIBANA_DOWNLOAD_URL="http://172.18.19.208/soft/elk/kibana-7.5.0-linux-x86_64.tar.gz"
TAR_PACKAGE_NAME=$(echo ${KIBANA_DOWNLOAD_URL}|awk -F '/' '{print $NF}')
DOWNLOAD_DIR="/data/src"
INSTALL_ROOT_DIR="/data/soft"
INSTALL_DIR=$(echo ${TAR_PACKAGE_NAME}|awk -F '.tar' '{print $1}')
KIBANA_HOME=${INSTALL_ROOT_DIR}/${INSTALL_DIR}
LINK="/data/kibana"
RUN_USER=elasticsearch
LOG_FILE=/tmp/install_kibana.log


# es相关配置
# IP=$(ifconfig|grep 'inet'|grep -v "127.0"|awk '{print $2}')
# ID=$(echo $${IP}|awk -F. '{print $3$4}')
# cluster_name="wsecar"
# node_name=node-$ID
# data_dir="/data/elasticsearch/data"





function _logging() {
	
	local color_start=$1
	local color_end=$2
	local level=$3
	local message=$4
	echo -e ${color_start}"[" `date +'%F %H:%M:%S'` "]" "[" $level "]" $message${color_end}|tee -a ${LOG_FILE}
};

function log_error() {
	local color_start='\033[31m'
	local color_end='\033[0m'
	_logging  ${color_start} ${color_end} 'ERROR' $1
};

function log_info() {
	local color_start='\033[32m'
	local color_end='\033[0m'
	_logging  ${color_start} ${color_end} 'INFO' $1
};

# 检查目录，木有则创建
function mk_dir() {
	local dest_dir=$1
	[[ -d ${dest_dir} ]]&&return $?

	mkdir -p ${dest_dir}
	if [[ $? -eq 0 ]];then
		log_info "${dest_dir}创建成功";
	else
		log_error "${dest_dir}创建失败，请检查.";exit 10;
	fi;
};

function untar_file() {
	local source_file=$1
	local dest_dir=$2
	mk_dir ${dest_dir}
	tar xf ${source_file} -C ${dest_dir}
	if [[ $? -eq 0 ]];then
		log_info "${source_file}解压成功."
	else
		log_error "${source_file}解压失败."
	fi;
};

function optimization() {
	# 修改最大线程数
	sed -i 's@*          soft    nproc.*@*          soft    nproc	32767@g' /etc/security/limits.d/20-nproc.conf
	grep 'vm.max_map_count' /etc/sysctl.conf
	if [[ $? -eq 0 ]];then
		sed -i 's@vm.max_map_count.*@vm.max_map_count=262144@g' /etc/sysctl.conf
	else
		echo 'vm.max_map_count=262144' >> /etc/sysctl.conf
	fi;

	sysctl -p
}

# 配置文件生成
# function config() {
# }

# 清空日志文件
> ${LOG_FILE}

[[ `whoami` == 'root' ]]||{ log_error '请使用root用户运行该脚本';exit 10; }


# 检查下载目录，安装目录是否存在，不存在则创建
mk_dir ${DOWNLOAD_DIR}
mk_dir ${INSTALL_ROOT_DIR}

#  检查下载目录并下载
cd ${DOWNLOAD_DIR} && curl -O ${KIBANA_DOWNLOAD_URL}
# 解压文件
untar_file ${TAR_PACKAGE_NAME} ${INSTALL_ROOT_DIR}

# 创建软连接
ln -sv ${KIBANA_HOME} ${LINK}

# 配置环境变量
echo "export KIBANA_HOME=${KIBANA_HOME}" > /etc/profile.d/elasticsearch.sh
echo "export PATH=\$PATH:$KIBANA_HOME/bin" >> /etc/profile.d/elasticsearch.sh
# 加载环境变量
source /etc/profile

# 创建执行用户

id ${RUN_USER}||useradd ${RUN_USER}
# 修改安装目录文件属主
chown -R ${RUN_USER}:${RUN_USER} ${KIBANA_HOME}
# 优化
optimization

# 配置文件自动生成.
# config





